package com.zhang.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.mysql.cj.util.StringUtils;
import com.zhang.gulimall.product.dao.*;
import com.zhang.gulimall.product.entity.*;
import com.zhang.gulimall.product.vo.AttrResponseVo;
import com.zhang.gulimall.product.vo.AttrVo;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhang.gulimall.common.utils.PageUtils;
import com.zhang.gulimall.common.utils.Query;

import com.zhang.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Resource
    AttrAttrgroupRelationDao relationDao;

    @Resource
    CategoryDao categoryDao;

    @Resource
    AttrGroupDao groupDao;

    @Resource
    ProductAttrValueDao productAttrValueDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.save(attrEntity);
        if (attr.getAttrType() == 1) {
            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
            entity.setAttrGroupId(attr.getAttrGroupId());
            entity.setAttrId(attrEntity.getAttrId());
            relationDao.insert(entity);
        }
    }

    @Transactional
    @Override
    public PageUtils queryBasePage(Map<String, Object> params, String id) {
        String key = (String) params.get("key");
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        if (!id.equals("0"))
            wrapper.lambda().eq(AttrEntity::getCatelogId, id);
        if (!key.isEmpty()) {
            String keys = (String) params.get("key");
            if (!StringUtils.isEmptyOrWhitespaceOnly(key)) {
                wrapper.lambda().like(AttrEntity::getAttrId, key).or().like(AttrEntity::getAttrName, keys);
            }
        }
        PageUtils pageUtils = new PageUtils(this.page(new Query<AttrEntity>().getPage(params), wrapper));
        pageUtils.setList(pageUtils.getList().stream().map((attrEntity) -> {
            AttrResponseVo responseVo = new AttrResponseVo();
            BeanUtils.copyProperties(attrEntity, responseVo);
            CategoryEntity categoryEntity = categoryDao.selectById(responseVo.getCatelogId());
            if (categoryEntity != null) {
                StringBuilder catelogName = new StringBuilder("/" + categoryEntity.getName());
                while (!categoryEntity.getParentCid().equals("0")) {
                    categoryEntity = categoryDao.selectById(categoryEntity.getParentCid());
                    catelogName.insert(0, "/" + categoryEntity.getName());
                }
                responseVo.setCatelogName(catelogName.toString());
            }
            QueryWrapper<AttrAttrgroupRelationEntity> wrapper1 = new QueryWrapper<>();
            wrapper1.lambda().eq(AttrAttrgroupRelationEntity::getAttrId, responseVo.getAttrId());
            AttrAttrgroupRelationEntity entity = relationDao.selectOne(wrapper1);
            if (entity != null) {
                AttrGroupEntity attrGroupEntity = groupDao.selectById(entity.getAttrGroupId());
                String attrGroupName = attrGroupEntity.getAttrGroupName();
                responseVo.setGroupName(attrGroupName);
            }
            return responseVo;
        }).distinct().collect(Collectors.toList()));
        return pageUtils;
    }

    @Override
    public AttrVo getDetailById(String attrId) {
        AttrEntity attrEntity = getById(attrId);
        AttrVo attrVo = new AttrVo();
        BeanUtils.copyProperties(attrEntity, attrVo);
        List<String> list = new ArrayList<>();
        list.add(attrVo.getCatelogId());
        CategoryEntity category = categoryDao.selectById(attrVo.getCatelogId());
        while (!category.getParentCid().equals("0")) {
            list.add(category.getParentCid());
            category = categoryDao.selectById(category.getParentCid());
        }
        Collections.reverse(list);
        attrVo.setCatelogPath(list.toArray(new String[0]));
        if (attrVo.getAttrType() == 1) {
            AttrAttrgroupRelationEntity entity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().lambda()
                    .eq(AttrAttrgroupRelationEntity::getAttrId, attrId));
            attrVo.setAttrGroupId(entity.getAttrGroupId());
        }
        return attrVo;
    }

    @Override
    public void updateDetail(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);
        AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
        BeanUtils.copyProperties(attr, entity);
        UpdateWrapper<AttrAttrgroupRelationEntity> wrapper = new UpdateWrapper<>();
        wrapper.lambda().eq(AttrAttrgroupRelationEntity::getAttrId, attr.getAttrId());
        relationDao.update(entity, wrapper);
    }

    @Override
    public PageUtils querySalePage(Map<String, Object> params, String id) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(AttrEntity::getCatelogId, id).eq(AttrEntity::getAttrType, 0).or().eq(AttrEntity::getAttrType, 2);
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<ProductAttrValueEntity> listBySpu(Map<String, Object> params, String spuId) {
        QueryWrapper<ProductAttrValueEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ProductAttrValueEntity::getSpuId, spuId);
        return productAttrValueDao.selectList(wrapper);
    }

    @Override
    public void updateAttr(List<ProductAttrValueEntity> list, String spuId) {
        list.forEach(attrValue -> {
            QueryWrapper<ProductAttrValueEntity> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(ProductAttrValueEntity::getAttrId, attrValue.getAttrId())
                    .eq(ProductAttrValueEntity::getSpuId, spuId);
            ProductAttrValueEntity productAttrValueEntity = productAttrValueDao.selectOne(wrapper);
            productAttrValueEntity.setAttrValue(attrValue.getAttrValue());
            productAttrValueEntity.setQuickShow(attrValue.getQuickShow());
            productAttrValueDao.updateById(productAttrValueEntity);
        });
    }

    @Override
    public List<ProductAttrValueEntity> listBySku(String skuId) {
        return null;
    }

//    @RabbitListener(queues = {"testQueue"})
//    public void listener(Message message, SkuInfoEntity skuInfoEntity){
//        System.out.println(skuInfoEntity);
//        System.out.println(1);
//    }
}